package OnTheBeach::Controller::Login;

use strict;
use warnings;
use base 'Catalyst::Controller';
use Digest::SHA1 qw/sha1_hex/;
=head1 NAME

OnTheBeach::Controller::Login - Catalyst Controller

=head1 DESCRIPTION

Catalyst Controller.

=head1 METHODS

=cut

=head2 index 

log them in, and if next_page is present redirect them to that page
Thanks plu!

=cut

sub index : Private {
	my ( $self, $c ) = @_;

	# Get the username and password from form
	my $username = $c->req->param('username');
	my $password = $c->req->param('password');
	$c->flash->{next_page} ||= $c->req->param('next_page');
	
        $c->log->debug("Username/password: $username, $password");
        $c->log->debug("Encrypted pass:" .  sha1_hex($password) );

	# If the username and password values were found in form
	if ( $username && $password ) {

		# Attempt to log the user in
		if ( $c->login( $username, $password ) ) {
			
			my $redirect_url;
			if ( defined $c->flash->{next_page} ) {
				
				$redirect_url = $c->uri_for( $c->flash->{next_page} )
				
			} else {
				
				$redirect_url = $c->uri_for( '/users/view', $username );
				
			}
			
			# If successful, then let them use the application
			$c->res->redirect( $redirect_url );

		}
		else {

			# Set an error message
			$c->stash->{error_msg} = "Bad username or password.";
			$c->stash->{template}  = 'login.tt2';
			return;

		}
	}

	# If either of above don't work out, send to the login page
	$c->stash->{template} = 'login.tt2';
}

=head1 AUTHOR

devin@onthebeachatnight.com

=head1 LICENSE

This library is free software, you can redistribute it and/or modify
it under the same terms as Perl itself.

=cut

1;
